﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using He.API.WeiXin;
using He.Common;
using He.Web.UI;

namespace He.Web.api.weixin
{
    public partial class index : System.Web.UI.Page
    {
        Model.wx_config wx_config = new BLL.wx_config().LoadConfig();
        protected void Page_Load(object sender, EventArgs e)
        {
            string signature = InputUtil.Get("signature");
            string timestamp = InputUtil.Get("timestamp");
            string nonce = InputUtil.Get("nonce");
            string echostr = InputUtil.Get("echostr");

            if (Request.HttpMethod == "GET")
            {
                //get method - 仅在微信后台填写URL验证时触发
                if (CheckSignature.Check(signature, timestamp, nonce, wx_config.token))
                {
                    Response.Write(echostr); //返回随机字符串则表示验证通过
                }
                else
                {
                    Response.Write("验证失败，请注意保持Token一致。");
                }
                Response.End();
            }
            else
            {
                //post method - 当有用户向公众账号发送消息时触发
                if (!CheckSignature.Check(signature, timestamp, nonce, wx_config.token))
                {
                    Response.Write("验证失败，请注意保持Token一致。");
                    return;
                }
                try
                {
                    MsgHandle response = new MsgHandle();
                    xml responseXml = response.ResponseNodes();//通过判断信息类型给属性赋值
                    string responseStr = ObjectConvert.ObjectToXmlSerializer(responseXml);//通过序列化将对象转换为xml字符串
                    Response.Write(responseStr);
                }
                catch (Exception ex)
                {
                    FileHelper.WriteLogTxt("~/log.txt", ex.ToString());
                }
            }
        }
    }
}